package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.msg.NewsUpOrDownMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-25 15:18
 */
@Component
@Slf4j
public class ArticleKafkaListener {

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleService apArticleService;

    @KafkaListener(topics = {WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC})
    public void downOrUp(String msg){
        //1.消息反序列化成对象
        if(StringUtils.isBlank(msg)){
            log.error("消息为空");
            return;
        }

        NewsUpOrDownMsg newsUpOrDownMsg = JSON.parseObject(msg, NewsUpOrDownMsg.class);

        //2.直接更新数据库
        apArticleConfigMapper.update(null, Wrappers.<ApArticleConfig>lambdaUpdate()
                .eq(ApArticleConfig::getArticleId,newsUpOrDownMsg.getArticleId())
                .set(ApArticleConfig::getIsDown, newsUpOrDownMsg.getEnable() == 1 ? 0: 1)
        );
    }

    @KafkaListener(topics = {HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC})
    public void behavior(String msg){
        if(StringUtils.isBlank(msg)){
            return;
        }
        ArticleVisitStreamMess mess = JSON.parseObject(msg, ArticleVisitStreamMess.class);
        apArticleService.updateArticleBehavior(mess);
    }
}
